using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class UI_LoadingIcon : MonoBehaviour
{
	[SerializeField]
	private RawImage loadingIcon;

	[SerializeField]
	private float fadeSpeed = 2f;

	private float targetOpacity;

	private Coroutine fadeCoroutine;

	public static UI_LoadingIcon Instance { get; private set; }

	private void Awake()
	{
		if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
		{
			Object.Destroy((Object)(object)((Component)this).gameObject);
			return;
		}
		Instance = this;
		Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
	}

	public static void ToggleLoadingIcon(bool showIcon)
	{
		if ((Object)(object)Instance == (Object)null)
		{
			Debug.LogError((object)"UI_LoadingIcon instance is not set. Make sure it's added to the scene.");
		}
		else if ((Object)(object)Instance.loadingIcon != (Object)null)
		{
			Instance.SetTargetOpacity(showIcon ? 1f : 0f);
		}
		else
		{
			Debug.LogError((object)"LoadingIcon RawImage is not assigned in the UI_LoadingIcon.");
		}
	}

	private void SetTargetOpacity(float opacity)
	{
		targetOpacity = opacity;
		if (fadeCoroutine != null)
		{
			((MonoBehaviour)this).StopCoroutine(fadeCoroutine);
		}
		fadeCoroutine = ((MonoBehaviour)this).StartCoroutine(FadeToTargetOpacity());
	}

	private IEnumerator FadeToTargetOpacity()
	{
		Color currentColor = ((Graphic)loadingIcon).color;
		while (!Mathf.Approximately(currentColor.a, targetOpacity))
		{
			currentColor.a = Mathf.MoveTowards(currentColor.a, targetOpacity, fadeSpeed * Time.deltaTime);
			((Graphic)loadingIcon).color = currentColor;
			yield return null;
		}
		fadeCoroutine = null;
	}
}
